package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.RedisValue;
import com.kingyun.gpsinspection.purificationservice.common.enums.TaskStatusEnum;
import com.kingyun.gpsinspection.purificationservice.common.enums.TaskTypeEnum;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.activiti.base.WorkFlowService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.IBMBPMService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.TaskService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by sugongche on 2016/12/19.
 */
public class TaskServiceImpl implements TaskService {
    public Logger logger = LoggerFactory.getLogger(this.getClass());

    // BPM
    @Autowired
    public IBMBPMService ibmbpmService;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private PatrolInspectionMapper patrolInspectionMapper;
    @Autowired
    private NormalOperationMapper normalOperationMapper;
    @Autowired
    private MaintenanceMapper maintenanceMapper;
    @Autowired
    private CheckRepairMapper checkRepairMapper;
    @Autowired
    private AnalysisProcessMapper analysisProcessMapper;
    @Autowired
    private ChangeManageMapper changeManageMapper;
    @Autowired
    private TerritorialSupervisionMapper territorialSupervisionMapper;
    @Autowired
    private WorkPermitMapper workPermitMapper;
    @Autowired
    private HazardIdentificationMapper hazardIdentificationMapper;
    @Autowired
    private MaterialsManageMapper materialsManageMapper;
    @Autowired
    private TdmWorkOrderMapper tdmWorkOrderMapper;
    @Autowired
    private WorkOrderEmployeeMapper workOrderEmployeeMapper;
    @Autowired
    private FlowCloseMapper flowCloseMapper;
    @Autowired
    private DailyThingsMapper dailyThingsMapper;
    @Autowired
    private WorkFlowService workFlowService;


    //BPM管理员账号
    @Value("#{configProperties['username']}")
    private String username;

    //BPM管理员密码
    @Value("#{configProperties['password']}")
    private String password;

    /**
     * 根据任务ID查询十大任务
     *
     * @param taskId
     * @return
     */
    @Override
    public Task findTaskByTaskId(String taskId) throws Exception {
        Task task = taskMapper.findTaskByTaskId(taskId);
        return task;
    }

    /**
     * 异步请求任务发起的table数据
     *
     * @param employeeVo
     * @param task       查询参数
     * @return
     */
    @Override
    public Map<String, Object> listMap(EmployeeVo employeeVo, Task task) throws Exception {
        Map<String, Object> map = new HashMap<>();
        task.setLimit(task.getLimit() == null ? 10 : task.getLimit());
        task.setOffset(task.getOffset() == null ? 0 : task.getOffset());
        task = formatIds(task);
        //设置过滤条件
        task.setFilterEmployeeId(employeeVo.getEmployeeId());
        task.setFilterOrgId(employeeVo.getOrgId());
        //分页查询记录
        List<Task> list = taskMapper.queryList(task);

        map.put("rows", list);
        map.put("total", taskMapper.queryCount(task));
        return map;
    }

    /**
     * 拆分多个id
     */
    private Task formatIds(Task task) {
        if (null != task.getOrgId() && task.getOrgId().contains(",")) {
            String[] str = task.getOrgId().split(",");
            task.setOrgIds(Arrays.asList(str));
            task.setOrgId(null);
        }
        return task;
    }

    /**
     * 异步请求与我相关的table数据：当前人发起或者当前人审核的任务
     * 思路：过滤当前登录人
     *
     * @param employeeVo
     * @param task
     * @return
     */
    @Override
    public Map<String, Object> listRelatedTaskMap(EmployeeVo employeeVo, Task task) throws Exception {
        Map<String, Object> map = new HashMap<>();
        task.setLimit(task.getLimit() == null ? 10 : task.getLimit());
        task.setOffset(task.getOffset() == null ? 0 : task.getOffset());
        //设置过滤条件：当前人只能看到自己相关的
        task.setUserId(employeeVo.getEmployeeId());
        //分页查询
        List<Task> list = taskMapper.queryRelatedList(task);

        map.put("rows", list);
        map.put("total", taskMapper.queryRelatedCount(task));

        return map;
    }

    /**
     * 异步请求子任务的table数据
     *
     * @param employeeVo
     * @param task
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> listChildTaskMap(EmployeeVo employeeVo, Task task) throws Exception {
        Map<String, Object> map = new HashMap<>();
        task.setLimit(task.getLimit() == null ? 10 : task.getLimit());
        task.setOffset(task.getOffset() == null ? 0 : task.getOffset());
        //分页查询
        List<Task> list = taskMapper.queryChildList(task);

        map.put("rows", list);
        map.put("total", taskMapper.queryChildCount(task));

        return map;
    }

    /**
     * 构造四大任务列表所需数据结构
     *
     * @param employeeVo
     * @param task
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> fourListMap(EmployeeVo employeeVo, Task task) throws Exception {
        Map<String, Object> map = new HashMap<>();
        task.setLimit(task.getLimit() == null ? 10 : task.getLimit());
        task.setOffset(task.getOffset() == null ? 0 : task.getOffset());
        List<Task> list = taskMapper.queryFourList(task);

        map.put("rows", list);
        map.put("total", taskMapper.queryFourCount(task));
        return map;
    }

    /**
     * 构造分析处理任务列表所需数据结构
     *
     * @param employeeVo
     * @param task
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> fxclListMap(EmployeeVo employeeVo, Task task) throws Exception {
        Map<String, Object> map = new HashMap<>();
        task.setLimit(task.getLimit() == null ? 10 : task.getLimit());
        task.setOffset(task.getOffset() == null ? 0 : task.getOffset());
        List<Task> list = taskMapper.queryFxclList(task);

        map.put("rows", list);
        map.put("total", taskMapper.queryFxclCount(task));
        return map;
    }

    /**
     * 构造危害因素辨识任务列表所需数据结构
     *
     * @param employeeVo
     * @param task
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> whysbsListMap(EmployeeVo employeeVo, Task task) throws Exception {
        Map<String, Object> map = new HashMap<>();
        task.setLimit(task.getLimit() == null ? 10 : task.getLimit());
        task.setOffset(task.getOffset() == null ? 0 : task.getOffset());
        List<Task> list = taskMapper.queryWhysbsList(task);

        map.put("rows", list);
        map.put("total", taskMapper.queryWhysbsCount(task));
        return map;
    }

    /**
     * 分页显示待办任务：旧方法不再采用
     *
     * @param redisValue
     * @param task       任务对象
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject listToDoTask(RedisValue redisValue, Task task) throws Exception {
        //String username = "deadmin";
        //String password = "deadmin";
        String username = redisValue.getLoginName();
        String password = redisValue.getPassWord();
        String result = ibmbpmService.queryToDoTask(username, password, "");

        JSONObject resultObj = JSONObject.parseObject(result);
        //获取data属性的值
        JSONObject dataObj = (JSONObject) resultObj.get("data");
        //获取items属性的值
        JSONArray itemsArray = (JSONArray) dataObj.get("items");

        Integer limit = task.getLimit() == null ? 10 : task.getLimit();
        Integer offset = task.getOffset() == null ? 0 : task.getOffset();

        //分页展示的JOSONArray
        JSONArray showArray = new JSONArray();
        //分页：遍历itemsArray
        //分页原理：当前页有数据，必然itemsArray.size()>offset
        if (itemsArray.size() > offset && itemsArray.size() >= offset + limit) { //23 > 10+10
            for (int i = offset; i < offset + limit; i++) {
                showArray.add(itemsArray.get(i));
            }
        } else if (itemsArray.size() > offset && itemsArray.size() < offset + limit) { //23<20+10
            for (int i = offset; i < itemsArray.size(); i++) {
                showArray.add(itemsArray.get(i));
            }
        } else if (itemsArray.size() <= offset) { //23<=30
        }

        //分页展示的JOSONObject
        JSONObject showObject = new JSONObject();
        showObject.put("total", itemsArray.size());
        showObject.put("rows", showArray);

        return showObject;
    }

    /**
     * 分页显示待办任务
     *
     * @param redisValue
     * @param task       任务对象
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject listToDoTaskMap(RedisValue redisValue, Task task) throws Exception {
        //String username = "deadmin";//用户名
        //String password = "deadmin";//密码

        String username = redisValue.getLoginName();//用户名
        String password = redisValue.getPassWord();//密码
        //获取人员信息
        EmployeeVo employeeVo = redisValue.getEmployeeVo();

        String result = ibmbpmService.queryToDoTask(employeeVo, username, password, assemblyQueryFilter(task), task.getLimit(), task.getOffset());//查询分页数据

        String countResult = ibmbpmService.queryToDoTaskCount(employeeVo, username, password, assemblyQueryFilter(task));//查询总记录条数

        /*处理查询出的数据*/
        JSONObject resultObj = JSONObject.parseObject(result);
        JSONObject countObj = JSONObject.parseObject(countResult);
        //获取data属性的值
        JSONObject dataObj = (JSONObject) resultObj.get("data");
        JSONObject countData = (JSONObject) countObj.get("data");
        //获取items属性的值
        JSONArray itemsArray = (JSONArray) dataObj.get("items");
        Integer count = (Integer) countData.get("count");

        if (itemsArray != null && itemsArray.size() > 0) {
            for (int i = 0; i < itemsArray.size(); i++) {
                JSONObject toDotask = (JSONObject) itemsArray.get(i);
                String PI_NAME = (String) toDotask.get("PI_NAME");
                String PI_PIID = (String) toDotask.get("PI_PIID");

                //查询任务发起信息
                Task t = getTaskInfo(PI_PIID);
                //判断非空
                if (t != null) {
                    //回设置值
                    ((JSONObject) itemsArray.get(i)).put("taskId", t.getId());
                    ((JSONObject) itemsArray.get(i)).put("taskName", t.getTaskName());
                    ((JSONObject) itemsArray.get(i)).put("createName", t.getCreateName());
                    ((JSONObject) itemsArray.get(i)).put("taskType", t.getTaskType());
                    ((JSONObject) itemsArray.get(i)).put("createTime", DateUtil.DateToString(t.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM));
                    ((JSONObject) itemsArray.get(i)).put("planStartTime", DateUtil.DateToString(t.getPlanStartTime(), DateStyle.YYYY_MM_DD_HH_MM));
                    ((JSONObject) itemsArray.get(i)).put("planEndTime", DateUtil.DateToString(t.getPlanEndTime(), DateStyle.YYYY_MM_DD_HH_MM));
                }
            }
        }


        //返回结果集
        JSONObject showObject = new JSONObject();
        showObject.put("total", count);
        showObject.put("rows", itemsArray);

        return showObject;
    }


    /**
     * 根据流程实例ID和任务类型名称查询任务发起相关信息
     *
     * @param PI_PIID
     * @return
     */
    public Task getTaskInfo(String PI_PIID) throws Exception {
        if (StringUtils.isBlank(PI_PIID)) {
            return null;
        }

        Task task = taskMapper.findTaskByFlowId(PI_PIID);

        return task;
    }

    /**
     * 拼装BPM查询条件
     *
     * @param task 查询条件封装类
     * @return
     */
    private String assemblyQueryFilter(Task task) throws Exception {

        String queryFilter = "";
        if (null == task)
            return queryFilter;
        /*封装查询条件*/
        if (null != task.getPiId() && task.getPiId() != "") {//流程实例ID
            queryFilter += (StringUtils.isBlank(queryFilter) ? "&queryFilter=PI_PIID=ID('" + encodeVal(task.getPiId()) + "')" : "%20AND%20PI_PIID=ID('" + encodeVal(task.getPiId()) + "')");
        }
        if (null != task.getTkiId() && task.getTkiId() != "") {//待办任务ID
            queryFilter += (StringUtils.isBlank(queryFilter) ? "&queryFilter=TKIID=ID('" + encodeVal(task.getTkiId()) + "')" : "%20AND%20TKIID=ID('" + encodeVal(task.getTkiId()) + "')");
        }
        if (null != task.getPiName() && task.getPiName() != "") {//流程类型
            queryFilter += (StringUtils.isBlank(queryFilter) ? "&queryFilter=PI_NAME%20LIKE%20'" + encodeVal(task.getPiName()) + "'" : "%20AND%20PI_NAME%20LIKE%20'" + encodeVal(task.getPiName()) + "'");
        }
        if (null != task.getOriginator() && task.getOriginator() != "") {//流程发起人
            queryFilter += (StringUtils.isBlank(queryFilter) ? "&queryFilter=ORIGINATOR%20LIKE%20'" + encodeVal(task.getOriginator()) + "'" : "%20AND%20ORIGINATOR%20LIKE%20'" + encodeVal(task.getOriginator()) + "'");
        }
        if (null != task.getRoleName() && task.getRoleName() != "") {//待办任务执行人角色
            queryFilter += (StringUtils.isBlank(queryFilter) ? "&queryFilter=ASSIGNED_TO_ROLE_DISPLAY_NAME%20LIKE%20'" + encodeVal(task.getRoleName()) + "'" : "%20AND%20ASSIGNED_TO_ROLE_DISPLAY_NAME%20LIKE%20'" + encodeVal(task.getRoleName()) + "'");
        }
        if (null != task.getName() && task.getName() != "") {//待办任务名称
            queryFilter += (StringUtils.isBlank(queryFilter) ? "&queryFilter=NAME%20LIKE%20'" + encodeVal(task.getName()) + "'" : "%20AND%20NAME%20LIKE%20'" + encodeVal(task.getName()) + "'");
        }
        if (null != task.getSnapshotName() && task.getSnapshotName() != "") {//流程版本名称
            queryFilter += (StringUtils.isBlank(queryFilter) ? "&queryFilter=SNAPSHOT_NAME%20LIKE%20'" + encodeVal(task.getSnapshotName()) + "'" : "%20AND%20SNAPSHOT_NAME%20LIKE%20'" + encodeVal(task.getSnapshotName()) + "'");
        }
        if (null != task.getSearch() && task.getSearch() != "") {//Search搜索框
            queryFilter = "&queryFilter=PI_NAME%20LIKE%20'" + encodeVal(task.getSearch()) + "'%20OR%20ORIGINATOR%20LIKE%20'" + encodeVal(task.getSearch()) + "'%20OR%20ASSIGNED_TO_ROLE_DISPLAY_NAME%20LIKE%20'" + encodeVal(task.getSearch()) + "'%20OR%20NAME%20LIKE%20'" + encodeVal(task.getSearch()) + "'%20OR%20SNAPSHOT_NAME%20LIKE%20'" + encodeVal(task.getSearch()) + "'";
        }
        return queryFilter;
    }

    /**
     * 将BPM查询条件中的中文进行转码
     *
     * @param val 原值
     * @return
     */
    private String encodeVal(String val) throws Exception {
        return null == val || val == "" ? null : URLEncoder.encode(val, "UTF-8");//将中文转码
    }

    /**
     * 保存自主任务
     *
     * @param task
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public String saveAutonomicTask(Task task, WorkOrder workOrder) {
        if (task.getTaskType() != null) {
            Short taskType = task.getTaskType();

            /*工单公共必填字段*/
            workOrder.setIsDownload((short) 1);
            workOrder.setStatus((short) 0);
            workOrder.setCanFinish((short) 1);
            workOrder.setIsDelete((short) 0);
            workOrder.setCreateUserId(workOrder.getCreateUserId());
            workOrder.setModifyUserId(workOrder.getCreateUserId());
            workOrder.setTaskType(taskType);
            /*工单公共必填字段*/

            if (taskType == 1) {
                PatrolInspection patrolInspection = new PatrolInspection();
                /*必填字段*/
                patrolInspection.setPatrolInspectionId(UniqueUtil.uuid());
                patrolInspection.setTaskType(taskType);
                patrolInspection.setTaskName(task.getTaskName());
                patrolInspection.setIsDelete((short) 0);
                patrolInspection.setIsEnable((short) 1);
                //工单上传执行结果：说明工单已经完成，任务已经完成
                patrolInspection.setTaskStatus((short) 3);
                patrolInspection.setCreateUserId(workOrder.getCreateUserId());
                patrolInspection.setModifyUserId(workOrder.getCreateUserId());
                /*必填字段*/
                patrolInspection.setPlanStartTime(workOrder.getStartTime());
                patrolInspection.setPlanEndTime(workOrder.getFinishTime());
                patrolInspection.setNode((short) 0);
                patrolInspection.setAuditStatus((short) 1);
                patrolInspection.setIsUsed((short) 0);
                //创建时间
                patrolInspection.setCreateTime(new Date());
                //修改时间
                patrolInspection.setModifyTime(new Date());
                patrolInspectionMapper.insert(patrolInspection);

                /*必填字段*/
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setTaskId(patrolInspection.getPatrolInspectionId());
                /*必填字段*/
                tdmWorkOrderMapper.insertNew(workOrder);

                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                /*必填字段*/
                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                workOrderEmployee.setEmployeeId(workOrder.getCreateUserId());
                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                /*必填字段*/
                workOrderEmployeeMapper.insert(workOrderEmployee);
            } else if (taskType == 2) {
                NormalOperation normalOperation = new NormalOperation();
                /*必填字段*/
                normalOperation.setNormalOperationId(UniqueUtil.uuid());
                normalOperation.setTaskType(taskType);
                normalOperation.setTaskName(task.getTaskName());
                normalOperation.setIsDelete((short) 0);
                normalOperation.setIsEnable((short) 1);
                //工单上传执行结果：说明工单已经完成，任务已经完成
                normalOperation.setTaskStatus((short) 3);
                normalOperation.setCreateUserId(workOrder.getCreateUserId());
                normalOperation.setModifyUserId(workOrder.getCreateUserId());
                /*必填字段*/
                normalOperation.setPlanStartTime(workOrder.getStartTime());
                normalOperation.setPlanEndTime(workOrder.getFinishTime());
                normalOperation.setNode((short) 0);
                normalOperation.setAuditStatus((short) 1);
                normalOperationMapper.insertNew(normalOperation);

                /*必填字段*/
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setTaskId(normalOperation.getNormalOperationId());
                /*必填字段*/
                tdmWorkOrderMapper.insertNew(workOrder);

                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                /*必填字段*/
                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                workOrderEmployee.setEmployeeId(workOrder.getCreateUserId());
                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                /*必填字段*/
                workOrderEmployeeMapper.insert(workOrderEmployee);
            } else if (taskType == 3) {
                Maintenance maintenance = new Maintenance();
                /*必填字段*/
                maintenance.setMaintenanceId(UniqueUtil.uuid());
                maintenance.setTaskType(taskType);
                maintenance.setTaskName(task.getTaskName());
                maintenance.setIsDelete((short) 0);
                maintenance.setIsEnable((short) 1);
                //工单上传执行结果：说明工单已经完成，任务已经完成
                maintenance.setTaskStatus((short) 3);
                maintenance.setCreateUserId(workOrder.getCreateUserId());
                maintenance.setModifyUserId(workOrder.getCreateUserId());
                /*必填字段*/
                maintenance.setPlanStartTime(workOrder.getStartTime());
                maintenance.setPlanEndTime(workOrder.getFinishTime());
                maintenance.setNode((short) 0);
                maintenance.setAuditStatus((short) 1);
                maintenance.setIsUsed((short) 0);
                //创建时间
                maintenance.setCreateTime(new Date());
                //修改时间
                maintenance.setModifyTime(new Date());
                maintenanceMapper.insert(maintenance);

                /*必填字段*/
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setTaskId(maintenance.getMaintenanceId());
                /*必填字段*/
                tdmWorkOrderMapper.insertNew(workOrder);

                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                /*必填字段*/
                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                workOrderEmployee.setEmployeeId(workOrder.getCreateUserId());
                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                /*必填字段*/
                workOrderEmployeeMapper.insert(workOrderEmployee);
            } else if (taskType == 4) {
                CheckRepair checkRepair = new CheckRepair();
                /*必填字段*/
                checkRepair.setCheckRepairId(UniqueUtil.uuid());
                checkRepair.setTaskType(taskType);
                checkRepair.setTaskName(task.getTaskName());
                checkRepair.setIsDelete((short) 0);
                checkRepair.setIsEnable((short) 1);
                //工单上传执行结果：说明工单已经完成，任务已经完成
                checkRepair.setTaskStatus((short) 3);
                checkRepair.setCreateUserId(workOrder.getCreateUserId());
                checkRepair.setModifyUserId(workOrder.getCreateUserId());
                /*必填字段*/
                checkRepair.setPlanStartTime(workOrder.getStartTime());
                checkRepair.setPlanEndTime(workOrder.getFinishTime());
                checkRepair.setNode((short) 0);
                checkRepair.setAuditStatus((short) 1);
                //创建时间
                checkRepair.setCreateTime(new Date());
                //修改时间
                checkRepair.setModifyTime(new Date());
                checkRepairMapper.insert(checkRepair);

                /*必填字段*/
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setTaskId(checkRepair.getCheckRepairId());
                /*必填字段*/
                tdmWorkOrderMapper.insertNew(workOrder);

                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                /*必填字段*/
                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                workOrderEmployee.setEmployeeId(workOrder.getCreateUserId());
                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                /*必填字段*/
                workOrderEmployeeMapper.insert(workOrderEmployee);
            } else if (taskType == 7) {
                TerritorialSupervision territorialSupervision = new TerritorialSupervision();
                /*必填字段*/
                territorialSupervision.setTerritorialSupervisionId(UniqueUtil.uuid());
                territorialSupervision.setTaskType(taskType);
                territorialSupervision.setTaskName(task.getTaskName());
                territorialSupervision.setIsDelete((short) 0);
                territorialSupervision.setIsEnable((short) 1);
                //工单上传执行结果：说明工单已经完成，任务已经完成
                territorialSupervision.setTaskStatus((short) 3);
                territorialSupervision.setCreateUserId(workOrder.getCreateUserId());
                territorialSupervision.setModifyUserId(workOrder.getCreateUserId());
                /*必填字段*/
                territorialSupervision.setPlanStartTime(workOrder.getStartTime());
                territorialSupervision.setPlanEndTime(workOrder.getFinishTime());
                territorialSupervision.setNode((short) 0);
                territorialSupervision.setAuditStatus((short) 1);
                //创建时间
                territorialSupervision.setCreateTime(new Date());
                //修改时间
                territorialSupervision.setModifyTime(new Date());
                territorialSupervisionMapper.insert(territorialSupervision);

                /*必填字段*/
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setTaskId(territorialSupervision.getTerritorialSupervisionId());
                /*必填字段*/
                tdmWorkOrderMapper.insertNew(workOrder);

                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                /*必填字段*/
                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                workOrderEmployee.setEmployeeId(workOrder.getCreateUserId());
                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                /*必填字段*/
                workOrderEmployeeMapper.insert(workOrderEmployee);
            } else if (taskType == 8) {
                WorkPermit workPermit = new WorkPermit();
                /*必填字段*/
                workPermit.setWorkPermitId(UniqueUtil.uuid());
                workPermit.setTaskType(taskType);
                workPermit.setTaskName(task.getTaskName());
                workPermit.setIsDelete((short) 0);
                workPermit.setIsEnable((short) 1);
                //工单上传执行结果：说明工单已经完成，任务已经完成
                workPermit.setTaskStatus((short) 3);
                workPermit.setCreateUserId(workOrder.getCreateUserId());
                workPermit.setModifyUserId(workOrder.getCreateUserId());
                /*必填字段*/
                workPermit.setPlanStartTime(workOrder.getStartTime());
                workPermit.setPlanEndTime(workOrder.getFinishTime());
                workPermit.setNode((short) 0);
                workPermit.setAuditStatus((short) 1);
                workPermitMapper.insertNew(workPermit);

                /*必填字段*/
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setTaskId(workPermit.getWorkPermitId());
                /*必填字段*/
                tdmWorkOrderMapper.insertNew(workOrder);

                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                /*必填字段*/
                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                workOrderEmployee.setEmployeeId(workOrder.getCreateUserId());
                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                /*必填字段*/
                workOrderEmployeeMapper.insert(workOrderEmployee);
                //没有工单的任务：工单ID范围空字符串
            } else {
                workOrder.setWorkOrderId("");
            }
        }

        String workOrderId = workOrder.getWorkOrderId();

        return workOrderId;
    }

    /**
     * 终止任务
     *
     * @param employeeVo
     * @param list
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int closeTaskByFlowIds(EmployeeVo employeeVo, List<String> list) {
        if (list == null) {
            return 0;
        }
        int a = 0;

        //String username = "deadmin";
        //String password = "deadmin";

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                String flowId = list.get(i);

                if (StringUtils.isNotBlank(flowId)) {
                    //终止BPM流程只是必须要求：不是终止任务的充分条件
                    String result = ibmbpmService.terminateBPM(username, password, flowId);

                    if ("".equals(result)) {
                        logger.error("流程终止获得返回值为空串！");
                    } else {
                        JSONObject resultObject = JSON.parseObject(result);

                        if (resultObject != null) {
                            JSONObject status = (JSONObject) resultObject.get("status");
                            if (status != null) {
                                logger.error("流程终止出现异常！");
                            }
                        } else {
                            logger.error("流程终止获得返回值为空串！");
                        }
                    }

                    //无论流程终止是否成功：任务均必须终止，解决已有历史任务流程终止但任务未终止
                    Task task = taskMapper.findTaskByFlowId(flowId);

                    if (task != null) {
                        Short taskType = task.getTaskType();
                        String taskId = task.getId();
                        //修改任务
                        a += modifyTask(taskType, taskId);

                        //工单置为无效
                        WorkOrder workOrder = new WorkOrder();
                        //工单终止
                        workOrder.setCanFinish((short) -1);
                        //工单异常关闭
                        workOrder.setStatus((short) 7);
                        workOrder.setTaskId(taskId);
                        workOrder.setModifyUserId(employeeVo.getEmployeeId());
                        //更新工单修改时间：必须，平板同步需要
                        workOrder.setModifyTime(new Date());
                        tdmWorkOrderMapper.updateByTaskIdSelective(workOrder);
                    }

                    FlowClose flowClose = new FlowClose();
                    flowClose.setFlowCloseId(UniqueUtil.uuid());
                    flowClose.setFlowId(flowId);
                    flowClose.setCloseUserId(employeeVo.getEmployeeId());
                    //非空判断
                    flowClose.setTaskId(task == null ? null : task.getId());
                    //非空判断
                    flowClose.setTaskType(task == null ? null : task.getTaskType());
                    a += flowCloseMapper.insertNew(flowClose);
                }
            }
        }

        return a;
    }

    /**
     * 终止任务
     *
     * @param employeeVo
     * @param list
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int closeTaskByTaskIds(EmployeeVo employeeVo, List<String> list) {
        if (list == null) return 0;
        int a = 0;
        if (list != null && list.size() > 0) {
            for (String id : list) {
                Task task = taskMapper.findTaskByTaskId(id);
                if (task != null) {
                    //是否周期任务
                    if (task.getIsPeriodicTask() == 0) {
                        //终止流程
                        if (null != task.getFlowId()) {
                            workFlowService.stopProcessInstance(task.getFlowId(), null);
                        }
                        //修改任务
                        a += modifyTask(task.getTaskType(), id);
                        //工单置为无效
                        WorkOrder workOrder = new WorkOrder();
                        //工单终止
                        workOrder.setCanFinish((short) -1);
                        //工单关闭
                        workOrder.setStatus((short) 7);
                        workOrder.setTaskId(id);
                        workOrder.setModifyUserId(employeeVo.getEmployeeId());
                        //更新工单修改时间：必须，平板同步需要
                        workOrder.setModifyTime(new Date());
                        a += tdmWorkOrderMapper.updateByTaskIdSelective(workOrder);
                    } else if (task.getIsPeriodicTask() == 1) {
                        /**
                         * 没有流程实例ID：必须判断是否是周期任务
                         * */
                        if (task.getTaskType() != null && task.getTaskType() == 1) {
                            PatrolInspection patrolInspection = new PatrolInspection();
                            patrolInspection.setTaskStatus((short) -1);
                            patrolInspection.setIsUsed((short) 1);
                            patrolInspection.setPatrolInspectionId(id);
                            a += patrolInspectionMapper.updateByPrimaryKeySelective(patrolInspection);
                        } else if (task.getTaskType() != null && task.getTaskType() == 3) {
                            Maintenance maintenance = new Maintenance();
                            maintenance.setTaskStatus((short) -1);
                            maintenance.setIsUsed((short) 1);
                            maintenance.setMaintenanceId(id);
                            a += maintenanceMapper.updateByPrimaryKeySelective(maintenance);
                        }
                        //工单置为无效
                        WorkOrder workOrder = new WorkOrder();
                        //工单终止
                        workOrder.setCanFinish((short) -1);
                        //工单关闭
                        workOrder.setStatus((short) 7);
                        workOrder.setTaskId(id);
                        workOrder.setModifyUserId(employeeVo.getEmployeeId());
                        //更新工单修改时间：必须，平板同步需要
                        workOrder.setModifyTime(new Date());
                        a += tdmWorkOrderMapper.updateByTaskIdSelective(workOrder);
                    } else {
                        return 0;
                    }
                }
            }
        }
        return a;
    }

    /**
     * 根据任务类型和任务id修改任务
     *
     * @param taskType 任务类型
     * @param taskId   任务id
     */
    private int modifyTask(Short taskType, String taskId) {
        if (taskType != null && taskType == 1) {
            PatrolInspection patrolInspection = new PatrolInspection();
            patrolInspection.setTaskStatus((short) -1);
            patrolInspection.setPatrolInspectionId(taskId);
            return patrolInspectionMapper.updateByPrimaryKeySelective(patrolInspection);
        } else if (taskType != null && taskType == 2) {
            NormalOperation normalOperation = new NormalOperation();
            normalOperation.setTaskStatus((short) -1);
            normalOperation.setNormalOperationId(taskId);
            return normalOperationMapper.updateByPrimaryKeySelective(normalOperation);
        } else if (taskType != null && taskType == 3) {
            Maintenance maintenance = new Maintenance();
            maintenance.setTaskStatus((short) -1);
            maintenance.setMaintenanceId(taskId);
            return maintenanceMapper.updateByPrimaryKeySelective(maintenance);
        } else if (taskType != null && taskType == 4) {
            CheckRepair checkRepair = new CheckRepair();
            checkRepair.setTaskStatus((short) -1);
            checkRepair.setCheckRepairId(taskId);
            return checkRepairMapper.updateByPrimaryKeySelective(checkRepair);
        } else if (taskType != null && taskType == 5) {
            AnalysisProcess analysisProcess = new AnalysisProcess();
            analysisProcess.setTaskStatus((short) -1);
            analysisProcess.setAnalysisProcessId(taskId);
            return analysisProcessMapper.updateByPrimaryKeySelective(analysisProcess);
        } else if (taskType != null && taskType == 6) {
            ChangeManage changeManage = new ChangeManage();
            changeManage.setTaskStatus((short) -1);
            changeManage.setChangeManageId(taskId);
            return changeManageMapper.updateByPrimaryKeySelective(changeManage);
        } else if (taskType != null && taskType == 7) {
            TerritorialSupervision territorialSupervision = new TerritorialSupervision();
            territorialSupervision.setTaskStatus((short) -1);
            territorialSupervision.setTerritorialSupervisionId(taskId);
            return territorialSupervisionMapper.updateByPrimaryKeySelective(territorialSupervision);
        } else if (taskType != null && taskType == 8) {
            WorkPermit workPermit = new WorkPermit();
            workPermit.setTaskStatus((short) -1);
            workPermit.setWorkPermitId(taskId);
            return workPermitMapper.updateByPrimaryKeySelective(workPermit);
        } else if (taskType != null && taskType == 9) {
            HazardIdentification hazardIdentification = new HazardIdentification();
            hazardIdentification.setTaskStatus((short) -1);
            hazardIdentification.setHazardIdentificationId(taskId);
            return hazardIdentificationMapper.updateByPrimaryKeySelective(hazardIdentification);
        } else if (taskType != null && taskType == 10) {
            MaterialsManage materialsManage = new MaterialsManage();
            materialsManage.setTaskStatus((short) -1);
            materialsManage.setMaterialsManageId(taskId);
            return materialsManageMapper.updateByPrimaryKeySelective(materialsManage);
        } else if (taskType != null && taskType == 11) {
            DailyThingsVo dailyThings = new DailyThingsVo();
            dailyThings.setTaskStatus((short) -1);
            dailyThings.setDailythingsId(taskId);
            return dailyThingsMapper.updateByPrimaryKeySelective(dailyThings);
        }
        return 0;
    }

    /**
     * 获取任务类型的柱状图data
     *
     * @param employeeVo
     * @return
     */
    @Override
    public String queryTaskTypePieChartData(EmployeeVo employeeVo) {
        Task task = new Task();
        //设置过滤条件
//        task.setFilterEmployeeId(employeeVo.getEmployeeId());
//        task.setFilterOrgId(employeeVo.getOrgId());
        TaskStatistics taskStatistics = taskMapper.selectTaskStatistics(task);
        JSONObject jsonObject = new JSONObject();
        Map<String, BigDecimal> map = new HashMap<>();
        for (TaskTypeEnum typeEnum : TaskTypeEnum.values()) {
            switch (typeEnum.getCode()) {
                case 1:
                    map.put(typeEnum.getDecription(), taskStatistics.getTask1());
                    break;
                case 2:
                    map.put(typeEnum.getDecription(), taskStatistics.getTask2());
                    break;
                case 3:
                    map.put(typeEnum.getDecription(), taskStatistics.getTask3());
                    break;
//                case 4:
//                    map.put(typeEnum.getDecription(), taskStatistics.getTask4());
//                    break;
                case 5:
                    map.put(typeEnum.getDecription(), taskStatistics.getTask5());
                    break;
//                case 6:
//                    map.put(typeEnum.getDecription(), taskStatistics.getTask6());
//                    break;
//                case 7:
//                    map.put(typeEnum.getDecription(), taskStatistics.getTask7());
//                    break;
//                case 8:
//                    map.put(typeEnum.getDecription(), taskStatistics.getTask8());
//                    break;
//                case 9:
//                    map.put(typeEnum.getDecription(), taskStatistics.getTask9());
//                    break;
//                case 10:
//                    map.put(typeEnum.getDecription(), taskStatistics.getTask10());
//                    break;
                case 11:
                    map.put(typeEnum.getDecription(), taskStatistics.getTask11());
                    break;
            }
        }
        JSONArray x = new JSONArray();
        JSONArray y = new JSONArray();
        for (String key : map.keySet()) {
            x.add(key);
            y.add(map.get(key));
        }
        //封装Y轴数据
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        object.put("color", "#F1565E");
        object.put("name", "任务");
        object.put("data", y);
        array.add(object);
        //封装最后一层
        jsonObject.put("x", x);
        jsonObject.put("y", array);
        return jsonObject.toString();
    }

    /**
     * 获取任务状态的柱状图data
     *
     * @param employeeVo
     * @return
     */
    @Override
    public String queryTaskStatusPieChartData(EmployeeVo employeeVo) {
        Task task = new Task();
        //设置过滤条件
//        task.setFilterEmployeeId(employeeVo.getEmployeeId());
//        task.setFilterOrgId(employeeVo.getOrgId());
        TaskStatistics taskStatistics = taskMapper.selectTaskStatistics(task);
        JSONObject jsonObject = new JSONObject();
        Map<String, BigDecimal> map = new HashMap<>();
        for (TaskStatusEnum statusEnum : TaskStatusEnum.values()) {
            switch (statusEnum.getCode()) {
                case 1:
                    map.put(statusEnum.getDecription(), taskStatistics.getStatus1());
                    break;
                case 2:
                    map.put(statusEnum.getDecription(), taskStatistics.getStatus2());
                    break;
                case 3:
                    map.put(statusEnum.getDecription(), taskStatistics.getStatus3());
                    break;
                case -1:
                    map.put(statusEnum.getDecription(), taskStatistics.getStatus4());
                    break;
            }
        }
        JSONArray x = new JSONArray();
        JSONArray y = new JSONArray();
        for (String key : map.keySet()) {
            x.add(key);
            y.add(map.get(key));
        }
        //封装Y轴数据
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        object.put("color", "#F1565E");
        object.put("name", "任务");
        object.put("data", y);
        array.add(object);
        //封装最后一层
        jsonObject.put("x", x);
        jsonObject.put("y", array);
        return jsonObject.toString();
    }

    /**
     * 获得当前处置人
     *
     * @param employeeVo
     * @param piPiid
     * @return
     */
    @Override
    public String queryCurrentDisposeName(EmployeeVo employeeVo, String piPiid) {
        String currentDisposeName = "";

        String result = ibmbpmService.queryToDoTask(employeeVo, username, password, "", piPiid);
        if ("".equals(result)) {
            logger.info("根据流程实例ID查询待办任务无返回值！");
        } else {
            JSONObject resultObj = JSONObject.parseObject(result);
            //获取data属性的值
            JSONObject dataObj = (JSONObject) resultObj.get("data");
            //获取items属性的值
            JSONArray itemsArray = (JSONArray) dataObj.get("items");

            //待办唯一：
            if (itemsArray != null && itemsArray.size() == 1) {
                JSONObject jsonObject = (JSONObject) itemsArray.get(0);
                currentDisposeName = (String) jsonObject.get("ASSIGNED_TO_ROLE_DISPLAY_NAME");
            }
        }

        return currentDisposeName;
    }


    /**
     * 查询待办任务总条数
     *
     * @param redisValue redis信息
     */
    public JSONArray queryToDoTaskCount(RedisValue redisValue) throws Exception {
        JSONArray jsonArray = new JSONArray();
        String username = redisValue.getLoginName();//用户名
        String password = redisValue.getPassWord();//密码
        EmployeeVo employeeVo = redisValue.getEmployeeVo(); //当前用户信息
        //查询总记录条数
        String countResult = ibmbpmService.queryToDoTaskCount(employeeVo, username, password, assemblyQueryFilter(null));
        /*处理查询出的数据*/
        JSONObject countObj = JSONObject.parseObject(countResult);
        //获取data属性的值
        JSONObject countData = (JSONObject) countObj.get("data");
        //获取items属性的值
        Integer count = (Integer) countData.get("count");
        //返回结果集
        JSONObject showObject = new JSONObject();
        showObject.put("navLabel", "待我处理任务");
        showObject.put("count", count);
        jsonArray.add(showObject);
        return jsonArray;
    }

    /**
     * 根据主任务ID，查询关联任务
     *
     * @param masterTaskId
     * @return
     */
    @Override
    public List<Task> findRelatedTasksByMasterTaskId(String masterTaskId) {
        List<Task> list = taskMapper.findRelatedTasksByMasterTaskId(masterTaskId);

        return list;
    }


    /**
     * 根据业务id查询流程的id
     *
     * @param BusinessId 业务id
     */
    public String getTaskIdByBusinessId(String BusinessId) {
        return taskMapper.getTaskIdByBusinessId(BusinessId);
    }
}
